﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace WebAPI.Filters
{
    //1. [ExceptionHandle]
    //2. [ServiceFilter(typeof(ExceptionHandle))] 依赖注入 services.AddScoped<ExceptionHandle>(); 需要在属性类中使用其他服务
    public class ExceptionHandle : ExceptionFilterAttribute
    {
        private readonly ILogger<ExceptionHandle> _logger;
        public ExceptionHandle(ILogger<ExceptionHandle> logger)
        {
            _logger = logger;
        }
        
        public override void OnException(ExceptionContext context)
        {
            var ex = context.Exception;
            var controllerName = context.RouteData.Values["controller"].ToString();
            var actionName = context.RouteData.Values["action"].ToString();
            
            // 异常中获取
            //var frame = new StackTrace(e, true).GetFrame(0);
            //controller = frame.GetMethod().DeclaringType.FullName;
            //action = frame.GetMethod().ToString();
            
            if (!context.ExceptionHandled) 
            {
                _logger.LogError(ex.Message, context.Exception);//调用
                
                context.Result = new JsonResult(new
                {
                    Result = false,
                    message = context.Exception.Message
                }) ; 
            }
            context.ExceptionHandled = true; //异常已处理了
            
            base.OnException(context);
            
            
            //当程序发生异常时执行的代码...
            //context.Result = context.HttpContext.Response.CreateResponse(
            //    System.Net.HttpStatusCode.InternalServerError,
            //    string.Format("异常：【{0}】已被捕获", context.Exception.Message));
        }
    }
}